//
//  CHCache.swift
//  yzb
//
//  Created by cyptt on 2022/1/10.
//

import UIKit
import HandyJSON

public class CHCache: NSObject {
    
    
    override init(){
        super.init()
    }
    
    /*
     缓存
     @param model 对象内容
     */
    public static func saveCache<T:HandyJSON>(model:T){
        
        let keyName = NSStringFromClass(T.self as! AnyClass)
        let jsonStr = model.toJSON()!
        let jsonData:Data? = try? JSONSerialization.data(withJSONObject: jsonStr, options: [])
        
        //       let chchePath:String = getCachePath() + keyName
        let chchePath:String = getHomeDocuments() + keyName
        let pathUrl:URL = URL.init(fileURLWithPath: chchePath)
        
        
        do {
            try jsonData?.write(to: pathUrl)
            
        }catch{
            print("读书缓存数据错误")
        }
    }
    
    /*
     缓存 需要传key
     @param model 对象内容
     @
     */
    public static func saveCache<T:HandyJSON>(model:T,key:String){
        
        let keyName = key
        let jsonStr = model.toJSON()!
        
        let jsonData:Data? = try? JSONSerialization.data(withJSONObject: jsonStr, options: [])
        
        //       let chchePath:String = getCachePath() + keyName
        
        let chchePath:String = getHomeDocuments() + keyName
        
        let pathUrl:URL = URL.init(fileURLWithPath: chchePath)
        
        
        do {
            try jsonData?.write(to: pathUrl)
            
        }catch{
            print("读书缓存数据错误")
        }
    }
    
    
    
    /**
     获取项目 缓存
     @param myType 项目类型
     */
    public static func getCache<T:HandyJSON>(myType:T.Type)->T?{
        
        let keyName = NSStringFromClass(myType.self as! AnyClass)
        let chchePath:String = getCachePath() + keyName   //兼容旧版
        
        let documentPath:String = getHomeDocuments() + keyName  //新版
        
        var strJsonDocument:String? = nil
        var strJson:String? = nil
        
        do{
            
            //            strJson = try String.init(contentsOfFile:chchePath )
            //            let model:T? = T.deserialize(from: strJson )
            
            strJsonDocument = try String.init(contentsOfFile: documentPath)
            
            let modelDocument:T? = T.deserialize(from: strJsonDocument )
            
            
            return modelDocument
        }catch {
            
            //读原来的
            do{
                
                strJson = try String.init(contentsOfFile:chchePath )
                let model:T? = T.deserialize(from: strJson )
                
                return model
            }catch {
                print("读书缓存数据错误")
                
                return nil
                
            }
            
            
        }
        
    }
    
    
    
    /**
     获取项目 缓存需要传key
     @param myType 项目类型
     @param key
     
     */
    public static func getCache<T:HandyJSON>(key:String)->T?{
        let keyName = key
        let chchePath:String = getCachePath() + keyName   //兼容旧版
        var strJson:String? = nil
        
        let documentPath:String = getHomeDocuments() + keyName  //新版
        var strJsonDocument:String? = nil
        
        do{
            strJsonDocument = try String.init(contentsOfFile: documentPath)
            let model:T? = T.deserialize(from: strJsonDocument )
            return model
        }catch {
            do{
                strJson = try String.init(contentsOfFile: chchePath)
                let model:T? = T.deserialize(from: strJson )
                return model
            }catch {
                print("读书缓存数据错误")
                return nil
                
            }
        }
        
    }
    
    /*
     清理缓存
     @param myType 类型
     
     @return  true 删除成功 false 删除不成功
     
     */
    public  static func clearCache<T:HandyJSON>(myType:T.Type)->Bool{
        let keyName = NSStringFromClass(myType.self as! AnyClass)
        let chchePath:String = getCachePath() + keyName
        let documentPath:String = getHomeDocuments() + keyName  //新版
        var isSuccess:Bool = false
        if FileManager.default.fileExists(atPath: chchePath) {
            do {
                try  FileManager.default.removeItem(atPath: chchePath)
                isSuccess = true
            }catch{
    
                isSuccess = false
                
            }
        }else{
            print("文件不存在")
            isSuccess = false
        }
        
        if FileManager.default.fileExists(atPath: documentPath) {
            do {
                try  FileManager.default.removeItem(atPath: documentPath)
                isSuccess = true
            }catch{
    
                isSuccess = false
                
            }
        }else{
            print("文件不存在")
            isSuccess = false
        }
        
        return isSuccess
    }
    
    /*
     清理缓存
     @param key 参数名
     @return  true 删除成功 false 删除不成功
     */
    public static func clearCache(key:String)->Bool{
        let keyName = key
        let chchePath:String = getCachePath() + keyName
        let documentPath:String = getHomeDocuments() + keyName  //新版
        if FileManager.default.fileExists(atPath: chchePath)  || FileManager.default.fileExists(atPath: documentPath)  {
            do {
                print("删除成功")
                try  FileManager.default.removeItem(atPath: chchePath)
                try  FileManager.default.removeItem(atPath: documentPath)
                return true
            }catch{
                print("删除失败")
                return false
            }
        }else{
            print("文件不存在")
            return false
        }
    }
    
   
    
}


//MARK: - 路径
extension CHCache{
    
    
    static func getHomeDocuments()->String{
        
        let path:String = NSHomeDirectory().appending("/Documents")
      
        let name:String = "/chAppCache/"
        let lastCache:String = path + name
        if(FileManager.default.fileExists(atPath: lastCache) == false){

            let laseCacheUrl:URL = URL.init(fileURLWithPath: lastCache)
            
            do {
                try FileManager.default.createDirectory(at: laseCacheUrl, withIntermediateDirectories: true, attributes: nil)
            }catch{
                print("创建chAppCache路径失败")
            }
        }
    
         return lastCache
    }
   
    
    /*
     创建Library/cache 路径
     */
   static func getCachePath()->String{
       let chchePath:String = NSHomeDirectory().appending("/Library/Caches")
     
       let name:String = "/chAppCache/"
       let lastCache:String = chchePath + name
       if(FileManager.default.fileExists(atPath: lastCache) == false){

           let laseCacheUrl:URL = URL.init(fileURLWithPath: lastCache)
           
           do {
               try FileManager.default.createDirectory(at: laseCacheUrl, withIntermediateDirectories: true, attributes: nil)
           }catch{
               print("创建chAppCache路径失败")
           }
       }
   
        return lastCache
    }
}

